#!/usr/bin/env python
# coding=utf-8
#__author__ = 'Yunchao Ling'

import sys
import ConfigParser
import time
import os

def checkSpace(dev):
    import commands
    import re

    space = 10
    line = commands.getoutput("df -B G -P")
    splitline = line.split("\n")
    for item in splitline:
        if item.startswith(dev):
            item = item.rstrip()
            regex = "^.*? *\d*G *\d*G *(\d*)G *\d*% *.*$"
            match = re.match(regex, item)
            if match:
                result = match.group(1)
                space = int(result)
                break
    return space

def countProcess():

    count=0
    for line in os.popen("ps xa"):
        line = line.rstrip()
        if line.find("sh pmc_workflow.sh") != -1:
            count += 1
    return count

if __name__ == "__main__":
    config = ConfigParser.ConfigParser()
    config.read(sys.argv[1])
    dev = config.get("node", "dev")

    start=int(sys.argv[2])
    end=int(sys.argv[3])

    current_worklist=start
    while current_worklist<=end:
        if os.path.exists("BLOCKED.IP"):
            sys.exit()
        if checkSpace(dev)>=5 and countProcess()==0:
            os.system("sh pmc_workflow.sh " + str(current_worklist)+" &")
            current_worklist+=1
        time.sleep(600)
